//
//  HECheckPictureViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2021/1/19.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HECheckPictureViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SNFCreditScoreCameraBaseView.h"
#import "UIDevice+ASMandatoryLandscapeDevice.h"
#import "LEEAlert.h"

@interface HECheckPictureViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>
//捕获设备，通常是前置摄像头，后置摄像头，麦克风（音频输入）
@property(nonatomic)AVCaptureDevice *device;

//AVCaptureDeviceInput 代表输入设备，他使用AVCaptureDevice 来初始化
@property(nonatomic)AVCaptureDeviceInput *input;

//当启动摄像头开始捕获输入
@property(nonatomic)AVCaptureMetadataOutput *output;

@property (nonatomic)AVCaptureStillImageOutput *ImageOutPut;

//session：由他把输入输出结合在一起，并开始启动捕获设备（摄像头）
@property(nonatomic)AVCaptureSession *session;

//图像预览层，实时显示捕获的图像
@property(nonatomic)AVCaptureVideoPreviewLayer *previewLayer;

@property (nonatomic)UIButton *PhotoButton;
@property (nonatomic)UIButton *flashButton;
@property (nonatomic)UIImageView *imageView;
@property (nonatomic)UIView *focusView;
@property (nonatomic)BOOL isflashOn;
@property (nonatomic)UIImage *image;

@property (nonatomic)BOOL canCa;
@property (nonatomic, strong) SNFCreditScoreCameraBaseView *baseView;


@end

@implementation HECheckPictureViewController

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self verticalScreen];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self mandatoryLandscape];

    _canCa = [self canUserCamear];
    if (_canCa) {
        [self customCamera];
        [self customUI];
    }
}

// 旋转屏幕
- (void)mandatoryLandscape {
    // 打开横屏开关
    kAppDelegate.allowOrentitaionRotation = YES;
    // 调用转屏代码
    [UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationLandscapeRight];
}

// 回到竖屏
- (void)verticalScreen {
    // 打开横屏开关
    kAppDelegate.allowOrentitaionRotation = NO;
    // 调用转屏代码
    [UIDevice deviceMandatoryLandscapeWithNewOrientation:UIInterfaceOrientationPortrait];
}

- (void)customUI{
    
    //遮罩区
    self.baseView = [[SNFCreditScoreCameraBaseView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth - 150, KScreenHeight)];
    [self.view addSubview:self.baseView];
    
    // 返回按钮 
    CGFloat back_width = 100;
    CGFloat back_height = 20;
    CGFloat top = 22;
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(0, top, back_width, back_height);
    [backButton setImage:[[UIImage imageNamed:@"back_icon"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];

    // 聚焦
//    _focusView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
//    _focusView.layer.borderWidth = 1.0;
//    _focusView.layer.borderColor =[UIColor greenColor].CGColor;
//    _focusView.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:_focusView];
//    _focusView.hidden = YES;
    
    // 黑色底部栏
    UIView *bottomView = [UIView new];
    bottomView.backgroundColor = UIColor.blackColor;
    [self.view addSubview:bottomView];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.equalTo(self.view);
        make.width.offset(150);
    }];
    
    // 拍摄按钮
    _PhotoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_PhotoButton setImage:[UIImage imageNamed:@"photograph"] forState: UIControlStateNormal];
    [_PhotoButton setImage:[UIImage imageNamed:@"photograph_Select"] forState:UIControlStateNormal];
    [_PhotoButton addTarget:self action:@selector(shutterCamera) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:_PhotoButton];
    
    [_PhotoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(bottomView);
        make.width.height.offset(60);
    }];
     
    // 提示按钮
    UIButton *noticeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [noticeBtn setBackgroundImage:IMAGE_NAMED(@"help2") forState:UIControlStateNormal];
    [noticeBtn addTarget:self action:@selector(showNotice) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:noticeBtn];
    
    [noticeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bottomView);
        make.top.equalTo(_PhotoButton.mas_bottom).offset(50);
        make.width.height.offset(22);
    }];
      
    // 闪光按钮
//    _flashButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    _flashButton.frame = CGRectMake(KScreenWidth-80, kScreenHeight-100, 80, 60);
//    [_flashButton setTitle:@"闪光灯关" forState:UIControlStateNormal];
//    [_flashButton addTarget:self action:@selector(FlashOn) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_flashButton];
//
//    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(focusGesture:)];
//    [self.view addGestureRecognizer:tapGesture];
}

- (void)customCamera{
    self.view.backgroundColor = [UIColor whiteColor];
    
    //使用AVMediaTypeVideo 指明self.device代表视频，默认使用后置摄像头进行初始化
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //使用设备初始化输入
    self.input = [[AVCaptureDeviceInput alloc]initWithDevice:self.device error:nil];
    
    //生成输出对象
    self.output = [[AVCaptureMetadataOutput alloc]init];
    self.ImageOutPut = [[AVCaptureStillImageOutput alloc] init];
 
    //生成会话，用来结合输入输出
    self.session = [[AVCaptureSession alloc]init];
    if ([self.session canSetSessionPreset:AVCaptureSessionPreset1280x720]) {
        
        self.session.sessionPreset = AVCaptureSessionPreset1280x720;
        
    }
    if ([self.session canAddInput:self.input]) {
        [self.session addInput:self.input];
    }
    
    if ([self.session canAddOutput:self.ImageOutPut]) {
        [self.session addOutput:self.ImageOutPut];
    }
    
    //使用self.session，初始化预览层，self.session负责驱动input进行信息的采集，layer负责把图像渲染显示
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    self.previewLayer.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight);
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.view.layer addSublayer:self.previewLayer];
    _previewLayer.connection.videoOrientation = [self videoOrientationFromCurrentDeviceOrientation];
    
    //开始启动
    [self.session startRunning];
    if ([_device lockForConfiguration:nil]) {
        if ([_device isFlashModeSupported:AVCaptureFlashModeAuto]) {
            [_device setFlashMode:AVCaptureFlashModeAuto];
        }
        //自动白平衡
        if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeAutoWhiteBalance]) {
            [_device setWhiteBalanceMode:AVCaptureWhiteBalanceModeAutoWhiteBalance];
        }
        [_device unlockForConfiguration];
    }
}

- (AVCaptureVideoOrientation) videoOrientationFromCurrentDeviceOrientation {
    switch (self.interfaceOrientation) {
        case UIInterfaceOrientationPortrait: {
           return AVCaptureVideoOrientationPortrait;
        }
        case UIInterfaceOrientationLandscapeLeft: {
           return AVCaptureVideoOrientationLandscapeLeft;
        }
        case UIInterfaceOrientationLandscapeRight: {
           return AVCaptureVideoOrientationLandscapeRight;
        }
        case UIInterfaceOrientationPortraitUpsideDown: {
           return AVCaptureVideoOrientationPortraitUpsideDown;
        }
    }
    return AVCaptureVideoOrientationLandscapeRight;
}

#pragma mark -
/**
 * 返回按钮事件
 */
- (void)cancelAction{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)showNotice {
    UIView *warp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 400, 200)];
   
    // 标题
    UILabel *titleLb = [UILabel new];
    titleLb.text = @"使用说明";
    titleLb.font = DYBlodFont(16);
    titleLb.textColor = KWhiteColor;
    titleLb.backgroundColor = CNavBgColor;
    titleLb.textAlignment = NSTextAlignmentCenter;
    [warp addSubview:titleLb];
    [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(warp).mas_offset(0);
        make.left.equalTo(warp).offset(0);
        make.right.equalTo(warp).offset(-0);
        make.height.mas_offset(40);
    }];
    
    
    // 内容
    QMUITextView *textView = [QMUITextView new];
    textView.text = @"1.尽量让检测卡充满取景框内的蓝色框线;\n2.尽量避免遮挡检测卡，以免阴影干扰扫描结果;\n3.手机摄像头尽量与检测卡保持水平;\n4.点击拍照按钮进行拍照;";
    textView.placeholderColor = UIColorPlaceholder; // 自定义 placeholder 的颜色
//    textView.textContainerInset = UIEdgeInsetsMake(5, 7, 5, 7);
    textView.typingAttributes = @{NSFontAttributeName: DYFont(16),
                                       NSParagraphStyleAttributeName: [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:20]
    };
    textView.editable = NO;
    textView.scrollEnabled = NO;
    textView.font = DYFont(16);
    textView.backgroundColor = KWhiteColor;
    [warp addSubview:textView];
    
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLb.mas_bottom).mas_offset(10);
        make.left.equalTo(warp).offset(15);
        make.right.equalTo(warp).offset(-15);
        make.height.mas_offset(120);
    }];
    
    // 检测按钮
    QMUIFillButton *cancelBtn = [[QMUIFillButton alloc] initWithFillColor:CNavBgColor titleTextColor:CNavBgFontColor];
    cancelBtn.titleLabel.font = UIFontMake(16);
    [cancelBtn setTitle:@"开始检测" forState:UIControlStateNormal];
    [warp addSubview:cancelBtn];

    [cancelBtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];

    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(warp.mas_bottom).offset(-(0 + 15));
        make.centerX.equalTo(warp);
        make.width.mas_offset(100);
        make.height.mas_offset(36);
    }];

    [LEEAlert alert].config
    .LeeHeaderInsets(UIEdgeInsetsMake(-10, 0, 0, 0))         // 头部内间距设置 等于内部项的范围
    .LeeMaxWidth(400) // 设置最大宽度 (固定数值 横竖屏相同)
    .LeeMaxHeight(200) // 设置最大高度 (固定数值 横竖屏相同)
    .LeeBackGroundColor(KWhiteColor)
    .LeeShouldAutorotate(YES) // 是否支持自动旋转 默认为NO
    .LeeSupportedInterfaceOrientations(UIInterfaceOrientationMaskAll)
    .LeeAddCustomView(^(LEECustomView *custom) {
        custom.view = warp;
        custom.isAutoWidth = YES;

//                custom.positionType = LEECustomViewPositionTypeRight;
    })
    .LeeItemInsets(UIEdgeInsetsMake(-10, 0, 10, 0))
    .LeeShow();
}

- (void)cancelClick {
    [LEEAlert closeWithCompletionBlock:^{
    }];
}

// 开启闪光
- (void)flashOn{
    if ([_device lockForConfiguration:nil]) {
        if (_isflashOn) {
            if ([_device isFlashModeSupported:AVCaptureFlashModeOff]) {
                [_device setFlashMode:AVCaptureFlashModeOff];
                _isflashOn = NO;
                [_flashButton setTitle:@"闪光灯关" forState:UIControlStateNormal];
            }
        }else{
            if ([_device isFlashModeSupported:AVCaptureFlashModeOn]) {
                [_device setFlashMode:AVCaptureFlashModeOn];
                _isflashOn = YES;
                [_flashButton setTitle:@"闪光灯开" forState:UIControlStateNormal];
            }
        }

        [_device unlockForConfiguration];
    }
}

// 切换摄像头
- (void)changeCamera{
    NSUInteger cameraCount = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo] count];
    if (cameraCount > 1) {
        NSError *error;
        
        CATransition *animation = [CATransition animation];
        
        animation.duration = .5f;
        
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        
        animation.type = @"oglFlip";
        AVCaptureDevice *newCamera = nil;
        AVCaptureDeviceInput *newInput = nil;
        AVCaptureDevicePosition position = [[_input device] position];
        if (position == AVCaptureDevicePositionFront){
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionBack];
            animation.subtype = kCATransitionFromLeft;
        }
        else {
            newCamera = [self cameraWithPosition:AVCaptureDevicePositionFront];
            animation.subtype = kCATransitionFromRight;
        }
        
        newInput = [AVCaptureDeviceInput deviceInputWithDevice:newCamera error:nil];
        [self.previewLayer addAnimation:animation forKey:nil];
        if (newInput != nil) {
            [self.session beginConfiguration];
            [self.session removeInput:_input];
            if ([self.session canAddInput:newInput]) {
                [self.session addInput:newInput];
                self.input = newInput;
                
            } else {
                [self.session addInput:self.input];
            }
            
            [self.session commitConfiguration];
            
        } else if (error) {
            NSLog(@"toggle carema failed, error = %@", error);
        }
        
    }
}

- (AVCaptureDevice *)cameraWithPosition:(AVCaptureDevicePosition)position{
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for ( AVCaptureDevice *device in devices )
        if ( device.position == position ) return device;
    return nil;
}

// 聚焦
- (void)focusGesture:(UITapGestureRecognizer*)gesture{
    CGPoint point = [gesture locationInView:gesture.view];
    [self focusAtPoint:point];
}

- (void)focusAtPoint:(CGPoint)point{
    CGSize size = self.view.bounds.size;
    CGPoint focusPoint = CGPointMake( point.y /size.height ,1-point.x/size.width );
    NSError *error;
    if ([self.device lockForConfiguration:&error]) {
        
        if ([self.device isFocusModeSupported:AVCaptureFocusModeAutoFocus]) {
            [self.device setFocusPointOfInterest:focusPoint];
            [self.device setFocusMode:AVCaptureFocusModeAutoFocus];
        }
        
        if ([self.device isExposureModeSupported:AVCaptureExposureModeAutoExpose ]) {
            [self.device setExposurePointOfInterest:focusPoint];
            [self.device setExposureMode:AVCaptureExposureModeAutoExpose];
        }
        
        [self.device unlockForConfiguration];
        _focusView.center = point;
        _focusView.hidden = NO;
        KWeakSelf
        [UIView animateWithDuration:0.3 animations:^{
            weakSelf.focusView.transform = CGAffineTransformMakeScale(1.25, 1.25);
        }completion:^(BOOL finished) {
            [UIView animateWithDuration:0.5 animations:^{
                weakSelf.focusView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                weakSelf.focusView.hidden = YES;
            }];
        }];
    }
    
}
#pragma mark - 截取照片
- (void) shutterCamera
{
    AVCaptureConnection * videoConnection = [self.ImageOutPut connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection) {
        NSLog(@"take photo failed!");
        return;
    }
    
    KWeakSelf
    [self.ImageOutPut captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        weakSelf.image = [UIImage imageWithData:imageData];
        [weakSelf.session stopRunning];
        [weakSelf saveImageToPhotoAlbum:weakSelf.image];
        weakSelf.imageView = [[UIImageView alloc]initWithFrame:weakSelf.previewLayer.frame];
        [weakSelf.view insertSubview:weakSelf.imageView belowSubview:weakSelf.PhotoButton];
        weakSelf.imageView.layer.masksToBounds = YES;
        weakSelf.imageView.image = weakSelf.image;
        NSLog(@"image size = %@",NSStringFromCGSize(weakSelf.image.size));
    }];
}
#pragma - 保存至相册
- (void)saveImageToPhotoAlbum:(UIImage*)savedImage
{

    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

}
// 指定回调方法

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo

{
    NSString *msg = nil ;
    if(error != NULL){
        msg = @"保存图片失败" ;
    }else{
        msg = @"保存图片成功" ;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"保存图片结果提示"
                                            message:msg
                                            delegate:self
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark - 检查相机权限
- (BOOL)canUserCamear{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alertView.tag = 100;
        [alertView show];
        return NO;
    }
    else{
        return YES;
    }
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0 && alertView.tag == 100) {
        
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url];
            
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
